<template>
  <div>
    <h2>HTML 片段转 PDF</h2>

    <textarea v-model="htmlContent" rows="10" style="width:100%; font-family: monospace;"></textarea>

    <button @click="exportToPDF">导出 PDF</button>

    <!-- 用于生成 PDF 的内容区域 -->
    <div
        ref="pdfContent"
        v-html="htmlContent"
        style="width: 800px; padding: 20px; background: white; margin-top: 20px;"
    ></div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

export default {
  data() {
    return {
      htmlContent: `<h1>PDF 示例</h1><p>这是示例内容，支持<b>HTML 标签</b>。</p>`.repeat(20),
    };
  },
  methods: {
    exportToPDF() {
      const content = this.$refs.pdfContent;// 获取 PDF 内容区域

      html2canvas(content, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
      }).then((canvas) => {
        const imgData = canvas.toDataURL("image/png");

        const pdf = new jsPDF("p", "mm", "a4");
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();

        const imgWidth = pageWidth;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        let position = 0;
        let remainingHeight = imgHeight;

        while (remainingHeight > 0) {
          pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
          remainingHeight -= pageHeight;
          if (remainingHeight > 0) {
            pdf.addPage();
            position = 0;
          }
        }

        pdf.save("内容导出.pdf");
      });
    },
  },
};
</script>

<style scoped>
button {
  margin-top: 10px;
  padding: 10px 20px;
  background: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}
button:hover {
  background: #369870;
}
</style>
